Skip to content

Latest commit

 

History

History
105 lines (96 loc) · 2.27 KB

File metadata and controls

105 lines (96 loc) · 2.27 KB

9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121 Output: true 

Example 2:

Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 

Example 3:

Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 

Follow up:

Coud you solve it without converting the integer to a string?

Solutions (Python)

1. Two Points

classSolution: defisPalindrome(self, x: int) ->bool: ifx<0: returnFalsen=0whilex// (10**n) !=0: n+=1n-=1whilex!=0: head=x// (10**n) tail=x%10ifhead==tail: x%=10**nx//=10n-=2else: returnFalsereturnTrue

2. Revert Left Half

classSolution: defisPalindrome(self, x: int) ->bool: ifx<0: returnFalsen=0whilex// (10**n) !=0: n+=1ifn%2==1: left=x// (10** (n//2+1)) else: left=x// (10** (n//2)) right=x% (10** (n//2)) rev=0whileleft!=0: rev*=10rev+=left%10left//=10returnrev==right

3. Revert Right Half

classSolution: defisPalindrome(self, x: int) ->bool: ifx<0or ((x%10) ==0andx!=0): returnFalserev=0whilex>rev: rev*=10rev+=x%10x//=10returnx==revorx== (rev//10)

Solutions (C)

1. Elementary Math

boolisPalindrome(intx){ intorigin=x; longsum=0; while(x>0) { sum=sum*10+x % 10; x /= 10; } if(sum==origin) { return true; } return false; }
close